package com.example.casper.Experiment2024.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import com.example.casper.Experiment2024.Database.AppDatabase;
import com.example.casper.Experiment2024.Database.GeoPoints;
import com.example.casper.Experiment2024.Database.PunchRecord;
import com.example.casper.Experiment2024.R;
import com.tencent.lbssearch.BuildConfig;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

public class TencentMapActivity extends Activity {
    private TextureMapView mapView;
    private TencentMap tencentMap;
    private ImageView footprintThumbnail;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tencent_map);

        mapView = findViewById(R.id.mapview_tencent);
        footprintThumbnail = findViewById(R.id.footprint_thumbnail);

        if (mapView == null) {
            Log.e("TencentMapActivity", "Failed to find mapView in the layout");
            return;
        }

        tencentMap = mapView.getMap();
        if (tencentMap == null) {
            Log.e("TencentMapActivity", "Failed to get TencentMap from mapView");
            return;
        }

        // 获取传递的经纬度数据
        Intent intent = getIntent();
        GeoPoints geoPoints = (GeoPoints) intent.getSerializableExtra("geo_points");
        intent.getSerializableExtra("geo_points");

        ArrayList<Double> longitudes = null;
        ArrayList<Double> latitudes = null;
        if (geoPoints != null) {
            latitudes = geoPoints.latitudes;
            longitudes = geoPoints.longitudes;
            // 使用这些经纬度数据
        }
        List<LatLng> latLngList = new ArrayList<>();
        if (latitudes != null && longitudes != null) {
            for (int i = 0; i < latitudes.size(); i++) {
                latLngList.add(new LatLng(latitudes.get(i), longitudes.get(i)));
            }
        }

        // 设置初始位置为最新打卡点或当前位置
        if (!latLngList.isEmpty()) {
            // 使用最新打卡点作为初始位置
            tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngList.get(latLngList.size() - 1), 15));

            // 在地图上绘制路径和标记
            tencentMap.addPolyline(new PolylineOptions().addAll(latLngList).color(0xFF0000FF).width(10));
            for (LatLng latLng : latLngList) {
                tencentMap.addMarker(new MarkerOptions().position(latLng).title("打卡点"));
            }
        } else {
            // 获取当前位置
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                // 权限已授予，获取当前位置
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (lastKnownLocation != null) {
                    LatLng currentLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                    tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
                } else {
                    // 如果无法获取当前位置，可以设置一个默认位置
                    LatLng defaultLocation = new LatLng(22.255453, 113.54145);
                    tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 15));
                }
            }
        }

        // 分享足迹按钮
        Button shareFootprintButton = findViewById(R.id.share_footprint_button);
        shareFootprintButton.setOnClickListener(v -> shareFootprint());

        // 截图分享按钮
        Button screenshotShareButton = findViewById(R.id.screenshot_share_button);
        screenshotShareButton.setOnClickListener(v -> screenshotAndShare());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以获取当前位置
                // 重新调用获取位置的逻辑
            } else {
                // 权限被拒绝，处理相应逻辑
            }
        }
    }

    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            // 当窗口获得焦点时生成足迹缩略图
            generateFootprintThumbnail();
        }
    }

    private void generateFootprintThumbnail() {
        AppDatabase db = AppDatabase.getInstance(this);
        List<PunchRecord> punchRecords = db.punchRecordDao().getAll(); // 获取所有打卡记录
        List<LatLng> latLngList = new ArrayList<>();

        // 提取经纬度
        for (PunchRecord record : punchRecords) {
            latLngList.add(new LatLng(record.getLatitude(), record.getLongitude()));
        }

        // 在地图上绘制路径
        if (!latLngList.isEmpty()) {
            tencentMap.addPolyline(new PolylineOptions().addAll(latLngList).color(0xFF0000FF).width(10)); // 绘制蓝色路径
        }

        // 生成足迹缩略图
        Bitmap thumbnailBitmap = createThumbnail(latLngList);
        footprintThumbnail.setImageBitmap(thumbnailBitmap);
    }

    private Bitmap createThumbnail(List<LatLng> latLngList) {
        int width = footprintThumbnail.getWidth();
        int height = footprintThumbnail.getHeight();
        if (width <= 0 || height <= 0) {
            // 可以使用默认尺寸或者返回 null 并稍后重试
            return null;
        }
        // 创建一个空白的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 在这里绘制路径到Bitmap上
        // TODO: 实现绘制路径到bitmap的逻辑
        return bitmap;
    }

    private void shareFootprint() {
        String footprintInfo = "这是我的足迹信息"; // 根据需要修改
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, footprintInfo);
        shareIntent.setType("text/plain");
        startActivity(Intent.createChooser(shareIntent, "分享足迹"));
    }

    public void screenshotAndShare() {
        mapView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(mapView.getDrawingCache());
        mapView.setDrawingCacheEnabled(false);

        try {
            File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "map_screenshot.png");
            FileOutputStream outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.flush();
            outputStream.close();

            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setType("image/png");
            startActivity(Intent.createChooser(shareIntent, "分享截图"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mapView != null) {
            mapView.onStart();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mapView != null) {
            mapView.onStop();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }
}